package com.sicilin.system.login.realm;

import com.sicilin.common.exception.ServiceException;
import com.sicilin.system.login.dto.LoginAuth;
import com.sicilin.system.login.dto.LoginRole;
import com.sicilin.system.login.dto.LoginUser;
import com.sicilin.system.login.service.LoginService;
import com.sicilin.system.user.Admin;
import com.sicilin.system.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class SystemShiroRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roleNames = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();

        String currentAccount = (String) SecurityUtils.getSubject().getPrincipal();
        if(currentAccount.equals("admin")){
            //当登陆用户是admin的时候，添加所有权限
            roleNames.add("administrator");//添加角色
            permissions.add("*");  //添加权限
        }else {
            LoginUser loginUser = loginService.getCurrentUser();
            for(LoginAuth auth:loginUser.getAuths()){
                permissions.add(auth.getAuthTotalCode());
            }
            for(LoginRole role:loginUser.getRoles()){
                roleNames.add(role.getRoleCode());
            }

        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        try {
            if(userService.isExistsUser(token.getUsername(),new String(token.getPassword()),1)){
                return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        throw new AuthenticationException();
    }
}
